package com.plian.system.service.im.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.office.WordUtil;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.entity.im.BaseInvestmentPlan;
import com.plian.system.entity.im.InvestmentPlanRecord;
import com.plian.system.mapper.im.InvestmentPlanRecordMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.im.IBaseInvestmentPlanService;
import com.plian.system.service.im.IInvestmentPlanRecordService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.vo.im.InvestmentPlanRecordVO;
import com.plian.system.wrapper.im.InvestmentPlanRecordWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @Author: Take-off
 * @Description: TODO
 * @Date: 2023/2/6 4:18 PM
 * @Version: 1.0
 **/
@Slf4j
@Service
@AllArgsConstructor
public class InvestmentPlanRecordServiceImpl extends BaseServiceImpl<InvestmentPlanRecordMapper,InvestmentPlanRecord> implements IInvestmentPlanRecordService {

    private final IFormCodeService formCodeService;

    private final InvestmentPlanRecordWrapper investmentPlanRecordWrapper;

    private Environment environment;

    private IBaseInvestmentPlanService baseInvestmentPlanService;
    @Override
    public boolean saveOrUpdate(InvestmentPlanRecord planRecord) {
        if (!Optional.ofNullable(planRecord.getId()).isPresent()) {
            planRecord.setRecordCode(formCodeService.getRecordCodeName(FormTypeConstant.IM_BASE_INVESTMENT_PLAN_RECORD));
            planRecord.setFormType(String.valueOf(FormTypeConstant.IM_BASE_INVESTMENT_PLAN_RECORD));
        }
        if (!Optional.ofNullable(planRecord.getRecordName()).isPresent()){
            planRecord.setRecordName("暂无名称");
        }
        boolean result = super.saveOrUpdate(planRecord);
        if (result){
            //保存备案Id
            Long planId = planRecord.getPlanId();
            if (Optional.ofNullable(planId).isPresent()){
                BaseInvestmentPlan plan = baseInvestmentPlanService.getById(planId);
                plan.setRecordId(planRecord.getId());
                baseInvestmentPlanService.updateById(plan);
            }
        }

        return result;
    }

    @Override
    public ListResult<InvestmentPlanRecordVO> list( Query query) {
        List<SearchEntity> entityList = query.getSearch();
        if (query.getAscs()==null&&query.getDescs()==null){
            query.setDescs("create_time");
        }
        QueryWrapper<InvestmentPlanRecord> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new InvestmentPlanRecord()), entityList
        );

        IPage<InvestmentPlanRecord> pages = page(Condition.getPage(query), queryWrapper);
        List<InvestmentPlanRecordVO> investmentPlanRecordVOS = investmentPlanRecordWrapper.entityToVO(pages.getRecords());
        ListResult<InvestmentPlanRecordVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(investmentPlanRecordVOS);
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }

    @Override
    public R<InvestmentPlanRecordVO> getDetailObj( InvestmentPlanRecord investmentPlanRecord) {
        InvestmentPlanRecord detail = getOne(Condition.getQueryWrapper(investmentPlanRecord));
        InvestmentPlanRecordVO investmentPlanRecordVO = investmentPlanRecordWrapper.entityToVO(detail);
        return R.data(investmentPlanRecordVO);
    }


    @Override
    public File buildword(InvestmentPlanRecord investmentPlanRecord, HttpServletResponse response) {
        InvestmentPlanRecordVO planRecordVO = investmentPlanRecordWrapper.entityToVO(investmentPlanRecord);
        File file = null;
        try {
            if (Optional.ofNullable(planRecordVO).isPresent()) {
                Map<String, String> data = new HashMap<>();
                data.put("orgName", planRecordVO.getOrgName());
                data.put("recordName", planRecordVO.getRecordName());
                data.put("code", planRecordVO.getRecordCode());
                data.put("quantity", planRecordVO.getRecordQuantity().toPlainString());

                String realPath = environment.getProperty("doc.path") + investmentPlanRecord.getId();
                //模版
                InputStream demo = this.getClass().getResourceAsStream("/pdf/investmentPlanRecordDemo.docx");

                file = WordUtil.downloadReportFile(data, realPath, "investmentPlanRecord.docx", demo);
                response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName());
                InputStream inputStream = new FileInputStream(file);
                // 激活下载操作
                OutputStream os = response.getOutputStream();
                // 循环写入输出流
                byte[] b = new byte[2048];
                int length;
                while ((length = inputStream.read(b)) > 0) {
                    os.write(b, 0, length);
                }
                // 这里主要关闭。
                os.close();
                inputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return file;
    }



}
